<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="98px"
    >
      <el-form-item label="项目名称" prop="postCode">
        <el-select v-model="queryParams.projectId" @change="projectChange" placeholder="项目名称">
          <el-option
            v-for="item in projectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="labs">
        <el-select v-model="queryParams.labs" multiple placeholder="选择标签">
          <el-option
            v-for="item in labsOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维度" prop="status">
        <el-select
          style="width: 110px"
          placeholder="维度"
          clearable
          v-model="queryParams.dimension"
        >
          <el-option
            v-for="item in scoreOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          style="width: 80px; margin-left: 10px"
          placeholder="条件"
          v-model="queryParams.comparison"
          clearable
        >
          <el-option lable=">" value=">"></el-option>
          <el-option lable="=" value="="></el-option>
          <el-option lable="<" value="<"></el-option>
        </el-select>
        <el-input-number
          v-model="queryParams.score"
          style="width: 120px; margin-left: 10px"
          controls-position="right"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="总分">
        <el-select
          style="width: 80px; margin-left: 10px"
          placeholder="条件"
          v-model="queryParams.scoreTotalComparison"
          clearable
        >
          <el-option lable=">" value=">"></el-option>
          <el-option lable="=" value="="></el-option>
          <el-option lable="<" value="<"></el-option>
        </el-select>
        <el-input-number
          v-model="queryParams.scoreTotal"
          style="width: 120px; margin-left: 10px"
          controls-position="right"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="是否通过" prop="passStatus">
        <el-select v-model="queryParams.passStatus" placeholder="是否通过" clearable>
          <el-option v-for="item in passOptions" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="margin-bottom: 16px">
      <el-button type="primary" size="mini" v-if="!isPlantform" @click="addCandidate"
        >添加候选人</el-button
      >
      <!-- <el-button type="primary" size="mini" @click="addCandidate">添加候选人</el-button> -->
      <el-button type="primary" size="mini" @click="openChartDialog" :disabled="!chartData.length"
        >查看评分</el-button
      >
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </div>

    <el-table
      v-loading="loading"
      :data="candidateList"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" width="120" />
      <el-table-column label="维度总分" align="center" prop="totalScore" sortable width="100" />
      <el-table-column label="各项维度分数" align="center" min-width="200">
        <template slot-scope="scope">
          <el-tag
            style="display: inline-block; margin-bottom: 4px; margin-right: 4px"
            v-for="tag in scope.row.scoreList"
            :key="tag.key"
          >
            {{ tag.key }}: {{ tag.value || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex" sortable />
      <el-table-column label="出生年月" align="center" prop="birthday" width="100" sortable />
      <!-- <el-table-column label="民族" align="center" prop="famous" /> -->
      <el-table-column label="身高" align="center" prop="height" sortable />
      <el-table-column label="体重" align="center" prop="weight" sortable />
      <el-table-column label="学校" align="center" prop="school" />
      <!-- <el-table-column label="专业" align="center" prop="major" /> -->
      <!-- <el-table-column label="籍贯" align="center" prop="hometown" /> -->
      <el-table-column label="是否单身" align="center" prop="dog" />
      <!-- <el-table-column label="昵称/外号" align="center" prop="nickName" /> -->
      <el-table-column label="职业" align="center" prop="work" />
      <el-table-column label="联系方式" align="center" prop="phone" v-if="!isPlantform" />
      <!-- <el-table-column label="现居地" align="center" prop="address" /> -->
      <el-table-column
        label="有/无经纪公司"
        align="center"
        prop="agent"
        min-width="120"
        show-overflow-tooltip
      />
      <!-- <el-table-column label="MBTI" align="center" prop="mbti" /> -->
      <el-table-column label="标签" align="center" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <el-tag
            style="display: inline-block; margin-bottom: 4px; margin-right: 4px"
            v-for="tag in scope.row.labNames"
            :key="tag"
          >
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="资料" align="center" min-width="100" max-width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
            >艺人资料</el-button
          >
        </template>
      </el-table-column>

      <el-table-column label="是否通过" align="center" width="120" v-if="!isPlantform">
        <template slot-scope="scope">
          <el-select
            placeholder="请选择"
            @change="passStatusChange($event, scope.row)"
            v-model="scope.row.passStatus"
          >
            <el-option v-for="item in passOptions" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="是否通过" align="center" width="80" v-else>
        <template slot-scope="{ row }">
          <el-tag v-if="row.passStatus == 1" type="success"> 通过 </el-tag>
          <el-tag v-else-if="row.passStatus == 0" type="danger"> 不通过 </el-tag>
          <el-tag v-else type="warning"> 待定 </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="评论" prop="projectComment" width="200" v-if="!isPlantform">
        <template slot-scope="scope">
          <el-input
            type="textarea"
            @blur="handleCommon(scope.row)"
            v-model="scope.row.projectComment"
            placeholder="请输入评论"
          ></el-input>
        </template>
      </el-table-column>

      <el-table-column label="评分" align="center" v-if="!isPlantform" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleScore(scope.row)"
            >评分</el-button
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
        v-if="!isPlantform"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasRole="['@systemAdmin']"
            style="color: #f56c6c"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <artist-detail ref="detail" />
    <score ref="score" @update="getList" />
    <el-dialog
      width="640px"
      :visible.sync="dialogVisible"
      title="维度查看"
      @open="updateChartData"
      @close="chartClose"
    >
      <div style="height: 600px; width: 600px">
        <RadarChart
          :legendData="legendData"
          :radarIndicator="radarIndicator"
          :seriesData="seriesData"
          v-if="dialogVisible"
        />
      </div>
    </el-dialog>

    <artist-edit
      ref="editForm"
      :visible.sync="showEditArt"
      :cand-info="selectRow"
      :projectOptions="projectOptions"
      @update="getList"
      v-if="showEditArt"
    />

    <choose-artist ref="addCandidate" @update="getList" :labsOption="labsOption" />

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listCandidate,
  setCandidateStatus,
  addCandidateComment,
  delCandidate
} from '@/api/system/candidate'
import { listProject, getProject } from '@/api/system/project'
import { listLab } from '@/api/system/lab'

import { transformData } from './dataTransformer.js'
import auth from '@/plugins/auth'
import RadarChart from '@/views/system/candidate/components/RadarChart.vue'
import artistDetail from './businessComponents/artistDetail.vue'
import score from './businessComponents/score.vue'
import artistEdit from './businessComponents/edit.vue'
import chooseArtist from './businessComponents/chooseArtist.vue'

export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  components: {
    RadarChart,
    artistDetail,
    score,
    artistEdit,
    chooseArtist
  },
  data() {
    return {
      showEditArt: false,
      projectOptions: [],
      labsOption: [],
      scoreOptions: [],
      passOptions: [
        {
          value: 1,
          label: '通过'
        },
        {
          value: 0,
          label: '不通过'
        },
        {
          value: -1,
          label: '待定'
        }
      ],

      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      candidateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        projectId: undefined,
        passStatus: undefined,
        labs: undefined,
        score: undefined,
        comparison: undefined,
        dimension: undefined,
        scoreTotal: undefined,
        scoreTotalComparison: undefined
      },
      dialogVisible: false,
      legendData: [],
      radarIndicator: [],
      seriesData: [],
      chartData: [],
      isPlantform: false,
      selectRow: null
    }
  },
  async created() {
    this.init()
    this.isPlantform = auth.hasRoleOr(['@platform'])
  },
  methods: {
    async init() {
      await this.getProjectList()
      this.queryParams.projectId = this.projectOptions ? this.projectOptions[0]?.value || '' : ''
      if (this.queryParams.projectId) {
        await this.getProjectDetail(this.queryParams.projectId)
      }
      await this.getList()
      this.getLabsList()
    },
    async getList() {
      this.loading = true
      const response = await listCandidate(this.queryParams)
      this.candidateList = response.rows.length
        ? response.rows.map(item => {
            const tempscoreList = item.projectScore ? JSON.parse(item.projectScore) : []
            return {
              ...item,
              ...item.sysArtistInfo,
              scoreList: tempscoreList,
              totalScore: tempscoreList.reduce((pre, cur) => {
                return pre + cur.value
              }, 0)
            }
          })
        : []
      this.total = response.total
      this.loading = false
    },
    async getProjectList() {
      const res = await listProject({
        pageNum: 1,
        pageSize: 999
      })
      this.projectOptions = res.rows.length
        ? res.rows.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        : []
    },
    getLabsList() {
      listLab({
        pageNum: 1,
        pageSize: 999
      }).then(response => {
        this.labsOption = response.rows.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      })
    },
    async getProjectDetail(id) {
      const res = await getProject(id)
      const projectScore = JSON.parse(res.data.projectScore)
      this.scoreOptions = projectScore.map(item => {
        return {
          label: item.key,
          value: item.key
        }
      })
    },
    projectChange(e) {
      this.queryParams.projectId = e
      this.getProjectDetail(e)
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.queryParams = {
        passStatus: undefined,
        labs: undefined,
        score: undefined,
        comparison: undefined,
        dimension: undefined,
        scoreTotal: undefined,
        scoreTotalComparison: undefined
      }
      this.resetForm('queryForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.chartData = selection.map(item => {
        return item
      })
    },
    handleDetail(row) {
      this.$refs['detail'].open(row)
    },
    /** 修改按钮操作 */
    handleScore(row) {
      this.$refs['score'].open(row)
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPost(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { projectId, artistId } = row
      this.$modal
        .confirm('是否确认从当前项目中移出候选人？')
        .then(function () {
          return delCandidate({
            projectId,
            artistId
          })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleEdit(row) {
      // let tempRow = JSON.parse(JSON.stringify(row))
      // tempRow = {
      //   ...tempRow,
      //   projectInfoList: tempRow.projectInfoList.map(item => {
      //     return {
      //       ...item,
      //       disabled: item.projectId != this.queryParams.projectId
      //     }
      //   })
      // }
      this.selectRow = null
      this.selectRow = row
      this.showEditArt = true
      // this.$refs.editForm.open('修改艺人管理', { ...tempRow, isEditCand: true })
    },
    handleCommon(row) {
      const { artistId, projectId, projectComment } = row
      addCandidateComment({
        artistId,
        projectId,
        projectComment
      }).then(res => {
        this.$modal.msgSuccess('操作成功')
        this.getList()
      })
    },
    passStatusChange(v, row) {
      const { artistId, projectId, passStatus } = row
      setCandidateStatus({
        artistId,
        projectId,
        passStatus
      }).then(res => {
        this.$modal.msgSuccess('操作成功')
        this.getList()
      })
    },
    updateChartData() {
      const { legendData, radarIndicator, seriesData } = transformData(this.chartData)

      this.legendData = legendData
      this.radarIndicator = radarIndicator
      this.seriesData = seriesData
      console.log(legendData)
    },

    openChartDialog(row) {
      if (row && row.id) {
        this.chartData.push(row)
      }
      this.dialogVisible = true
    },
    chartClose() {
      this.chartData = []
      this.dialogVisible = false
      this.$refs.multipleTable.clearSelection()
    },
    addCandidate() {
      this.$refs.addCandidate.open(this.queryParams.projectId)
    }
  }
}
</script>
